package com.hontech.desktoppastacooker.conn.serial

import com.hontech.desktoppastacooker.codec.decodeUint8
import com.hontech.bv.codec.encodeUint8
import com.hontech.desktoppastacooker.utils.toHex

class ByteView (var data: ByteArray = byteArrayOf(), var index: Int = 0, var len: Int = data.size - index) :
    SerialType {

    override fun size(): Int {
        return 1 + len
    }

    override fun encode(buf: ByteArray, offset: Int) {
        encodeUint8(buf, offset, len)
        System.arraycopy(data, index, buf, offset + 1, len)
    }

    override fun decode(buf: ByteArray, offset: Int) {
        len = decodeUint8(buf, offset)
        data = buf
        index = offset + 1
    }

    override fun toString(): String {
        return String(data, index, len)
    }

    fun toHex(): String {
        return data.toHex(index, len)
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as ByteView

        if (len != other.len) return false

        for (i in 0 until len) {
            if (data[index + i] != other.data[other.index + i]) {
                return false
            }
        }
        return true
    }

    override fun hashCode(): Int {
        var result = data.contentHashCode()
        result = 31 * result + index
        result = 31 * result + len
        return result
    }
}


